// $(document).ready(function() {
$(function() {
  var currentOperation; //用于存放当前操作
  var selectBoxBackGroundColor; // 选择框背景颜色
  var selectBox = new SelectBox(); //申明一个box来存当前操作的选框


  //--初始化三个 用于存放 最终形成的 选框 坐标宽高等数据的 变量 用于传给服务端处理拼合
  var signatoryBox = []; //对应 test1 区域存放
  var senderBox = new Array(); //对应 test2 区域存放
  var signBox = new Array(); //对应 test3 区域存放


  var selected = new Array(); //注册一个选取框 用于 选取操作

  var flag; //申明一个用来预存选取区域的大图

  var isSelecingStart = false; //是否开启选框

  var _isFlag = false; //是否点击过完成按钮，（判断滚动条）

  var _eleFlag = '' //记录当前是选择的那个选框按钮
  var contAdd = 0; //添加多个DOM元素的唯一值

  var newcontAdd = 0; //绘制多个DOM元素的唯一值
  var ttt = false;
  var saveCont = 0

  // setMaskWidth:动态设置遮罩层高宽
  var setMaskWidth = $('#content').innerWidth()
  var setMaskHeight = $('#content').prop('scrollHeight')
  $("#mask").css('width', setMaskWidth)
  $('#mask').css('height', setMaskHeight)

  //-----显示mask
  var btns = $('.btn_box input')
  $.each(btns, function(i, item) {
    $(item).on('click', function() {
      if ($(item).hasClass('clicked')) {
        return
      }
      $(item).addClass('clicked')
      _isFlag = true
      var parentIdName = $(item).attr('id')
      _eleFlag = parentIdName
      //动态创建选择框
      // console.log(contAdd)
      var createBox = appendText('selectRecBox' + parentIdName, 'RecBoxIsSelected' + parentIdName, contAdd)
      $('#constituency-warp').append(createBox)

      $('#controllHandle').addClass('notBg')
      if ($("#mask").is(":hidden")) {
        $("#mask").show(); //如果mask为隐藏,则将它显现
      }
      //当前操作
      currentOperation = parentIdName + contAdd; //绘制DOM元素的唯一值
      // console.log(currentOperation);
      selected = [];
      flag = new BigMapObj('mask');
    })
  })

  // 添加
  var aBtn = $('.btn_box a')
  $.each(aBtn, function(i, item) {
    $(item).on('click', function() {
      _isFlag = true
      var parentIdName = $(item).attr('class')
      _eleFlag = parentIdName
      //动态创建选择框
      contAdd++;
      // console.log(contAdd)
      var createBox = appendText('selectRecBox' + parentIdName, 'RecBoxIsSelected' + parentIdName, contAdd)
      $('#constituency-warp').append(createBox)

      $('#controllHandle').addClass('notBg')
      if ($("#mask").is(":hidden")) {
        $("#mask").show(); //如果mask为隐藏,则将它显现
      }
      //当前操作
      currentOperation = parentIdName + contAdd; //绘制DOM元素的唯一值
      // console.log(currentOperation);
      selected = [];
      flag = new BigMapObj('mask');
    })
  })
  //-----隐藏mask
  $("#complete").click(function() {
    _isFlag = false
    $('.btn_box input').removeClass('clicked')
    $('#controllHandle').removeClass('notBg')
    if ($("#mask").is(":visible")) {
      $("#mask").hide(); //如果mask为隐藏,则将它显现
    }
  });
  /*
   * 鼠标越界或非法反向操作
   */
  $("#mask").hover(
    function() { //预览框里边
      //console.log("a"); 此空函数不能删
    },
    function() { //预览框外边
      if (isSelecingStart) { //如果选框状态已开启
        selectBox.setEmpty(currentOperation);
        selected = [];
        isSelecingStart = false; //关闭选框状态
      }
    }
  );
  /*
   *滚动条
   */
  $('#mask').scroll(function() {
    console.log('55')
    // console.log($('#controllHandle').scrollTop()+'px')
  });
  /*
   *鼠标按下
   */
  $("#controllHandle").mousedown(function(event) {
    if (_isFlag) {
      isSelecingStart = true; //开启选框状态
      var point = getMousePoint(event); //---获取当前鼠标位置
      // console.log(point)
      if (flag.isCover(point.x, point.y)) {
        selectBox.setStartPoint(point.x, point.y);
        // console.log(point.x, point.y)
      } else {
        selected = [];
      }
    }

  });
  /*
   *鼠标移动
   */
  $("#controllHandle").mousemove(function(event) {
    if (_isFlag) {
      if (isSelecingStart) { //如果选框状态已开启
        var point = getMousePoint(event); //---获取当前鼠标位置
        if (flag.isCover(point.x, point.y)) {
          selectBox.setRect(currentOperation);
          selectBox.setEndPoint(point.x, point.y);
        } else {
          selected = [];
        }
      }
    }
  });
  /*
   *鼠标弹起
   */
  $("#controllHandle").mouseup(function(event) {
    if (_isFlag) {
      if (isSelecingStart) { //如果选框状态已开启
        var point = getMousePoint(event); //---获取当前鼠标位置
        if (flag.isCover(point.x, point.y)) {
          selectBox.setEndPoint(point.x, point.y);
          selectBox.refreshs();
          selectBox.setRect(currentOperation);
          selected = selectBox.getSelected();
        } else {
          selected = [];
        }
        isSelecingStart = false; //关闭选框状态
      }
      if (selected !== "undefined" && selected.length != 0) {

        selected[0] = selected[0] - flag.x1;
        selected[1] = selected[1] - flag.y1;
        selected[2] = selected[2] - flag.x1;
        selected[3] = selected[3] - flag.y1;
        // console.log(currentOperation)
        //针对每次不同的添加存储到对应数组内
        var newStr = currentOperation;







        switch (currentOperation) { // 整个switch 用于 分别存储 不同的 区域
          case `SignName${contAdd}`:
            var newArrStr = newStr.split('e')[1]
            if (`SignName${newArrStr}`) {
              signatoryBox[newArrStr] = selected
              console.log('第一个:',signatoryBox);
            }
            break;
          case `Ours${contAdd}`:
            var ourArrStr = newStr.split('s')[1]
            if (`Ours${ourArrStr}`) {
              senderBox[ourArrStr] = selected
              console.log('第二个:',senderBox);
              console.log(senderBox.length)

            }
            break;
          case `Others${contAdd}`:
            var otherArrStr = newStr.split('s')[1]
            if (`Others${otherArrStr}`) {
              signBox[otherArrStr] = selected
              console.log('第三个:',signBox);
            }
            break;
        }
        // console.log(signatoryBox);
        // console.log(senderBox);
        // console.log(signBox);
      }

    }

  });


});

//   function clear_arr_trim(array) {
//     for (var i = 0; i < array.length; i++) {
//       if (array[i] == "" || typeof(array[i]) == "undefined") {
//           array.splice(i, 1);
//           i = i - 1;
//         }
//       }
//       return array;
//       console.log(array)
//     }
//   }

// 动态创建(多个dom元素的contAdd值)
function appendText(IdName, className, contAdd) {
  // contAdd++;
  // console.log(contAdd)
  var cont = "<div id=" + IdName + contAdd + " class=" + className + "></div>"; // 以 HTML 创建新元素
  // $("parent").append(cont); // 追加新元素
  return cont
}
/*
 *框选状态的区域对象
 */
function SelectBox() {
  // console.log(contAdd)
  this.x1 = 0;
  this.y1 = 0;
  this.x2 = 0;
  this.y2 = 0;
  this.left = 0;
  this.width = 0;
  this.top = 0;
  this.height = 0;
  this.setStartPoint = function(x1, y1) {
    this.x1 = x1;
    this.y1 = y1;
    //this.refresh();
  };
  this.setEndPoint = function(x2, y2) {
    this.x2 = x2;
    this.y2 = y2;
    this.refreshs();
  };
  this.setPoint = function(x1, y1, x2, y2) {
    this.setStartPoint(x1, y1);
    this.setEndPoint(x2, y2);
    this.refreshs();
    console.log(this.x1);
  };
  this.refreshs = function() {
    if (this.x2 >= this.x1) {
      this.left = parseInt(this.x1);
      this.width = parseInt(this.x2 - this.x1);
    } else {
      this.left = parseInt(this.x2);
      this.width = parseInt(this.x1 - this.x2);
    }
    if (this.y2 >= this.y1) {
      this.top = parseInt(this.y1);
      this.height = parseInt(this.y2 - this.y1);
    } else {
      this.top = parseInt(this.y2);
      this.height = parseInt(this.y1 - this.y2);
    }
  };
  this.setRect = function(currentOperation) {
    // console.log(contAdd)
    // console.log($('#selectRecBox1' + currentOperation));
    // console.log(newcontAdd+=1)
    $('#selectRecBox' + currentOperation).css({
      'top': this.top,
      'left': this.left,
      'height': this.height,
      'width': this.width
    });
    // console.log('dfdfdf');
  };
  this.setEmpty = function(currentOperation) {
    $('#selectRecBox' + currentOperation).css({
      'top': 0,
      'left': 0,
      'height': 0,
      'width': 0
    });
  }
  this.getSelected = function() {
    if (this.x2 >= this.x1) {
      var startX = this.x1;
      var endX = this.x2;
    } else {
      var startX = this.x2;
      var endX = this.x1;
    }
    if (this.y2 >= this.y1) {
      var startY = this.y1;
      var endY = this.y2;
    } else {
      var startY = this.y2;
      var endY = this.y1;
    }
    var selected = new Array();
    selected[0] = startX;
    selected[1] = startY;
    selected[2] = endX;
    selected[3] = endY;
    return selected;
  };
}
/*
 *获取当前控件位置
 */
function getCurrentElementPosition(elementId) {
  this.offset = $('#' + elementId).offset();
  this.width = $('#' + elementId).width();
  this.height = $('#' + elementId).height();
  var container = {
    top: this.offset.top,
    left: this.offset.left,
    width: this.width,
    height: this.height
  };

  return container;
}
/*
 *框选区域对象合法性判断
 */
function BigMapObj(elementId) {
  this.currentContractPosition = getCurrentElementPosition(elementId); //获取预览区域位置坐标和宽高
  this.x1 = this.currentContractPosition.left; //大图的起点X
  this.y1 = this.currentContractPosition.top; //大图的起点Y
  this.x2 = this.x1 + this.currentContractPosition.width; //大图的终点X
  this.y2 = this.y1 + this.currentContractPosition.height; //大图的终点Y
  //判断点(x,y)是否在合法区域内
  this.isCover = function(x, y) {
    var inside = false;
    if (this.x1 < x && x < this.x2) {
      if (this.y1 < y && y < this.y2) {
        inside = true;
      }
    }
    return inside;
  };
}
/*
 *获取鼠标位置
 */
function getMousePoint(ev) {
  //获取
  var div = document.getElementById("mask");
  var e = event || window.event;
  var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
  var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
  var x = e.pageX || e.clientX + scrollX;
  var y = e.pageY || e.clientY + scrollY;
  //alert('x: ' + x + '\ny: ' + y);
  //获取元素的滚动Y坐标
  var YY = $('#controllHandle').scrollTop() - 40;
  var objtop = $('#controllHandle').offset().top;
  var objleft = $('#controllHandle').offset().left;
  // console.log(x, y + YY);

  // 定义鼠标在视窗中的位置
  var point = {
    x: 0,
    y: 0
  };
  point.x += x - objleft;
  point.y += y + YY - objtop;
  // point.x=event.clientX+document.body.scrollLeft||document.documentElement.scrollLeft;
  // point.y = event.clientY+document.body.scrollTop||document.documentElement.scrollTop;
  // 如果浏览器支持 pageYOffset, 通过 pageXOffset 和 pageYOffset 获取页面和视窗之间的距离
  // if (typeof window.pageYOffset != 'undefined') {
  // 	point.x = window.pageXOffset;
  // 	point.y = window.pageYOffset;
  // }
  // 如果浏览器支持 compatMode, 并且指定了 DOCTYPE, 通过 documentElement 获取滚动距离作为页面和视窗间的距离
  // IE 中, 当页面指定 DOCTYPE, compatMode 的值是 CSS1Compat, 否则 compatMode 的值是 BackCompat
  // else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') {
  // 	point.x = document.documentElement.scrollLeft;
  // 	point.y = document.documentElement.scrollTop;
  // }
  // 如果浏览器支持 document.body, 可以通过 document.body 来获取滚动高度
  // else if (typeof document.body != 'undefined') {
  // 	point.x = document.body.scrollLeft;
  // 	point.y = document.body.scrollTop;
  // }
  // 加上鼠标在视窗中的位置
  // point.x += ev.clientX;
  // point.y += ev.clientY;
  // 返回鼠标在视窗中的位置
  return point;
}
/*
 *判断两个class 属性的  div有没有交集
 */
function isOverlapped(ClassOne, ClassTwo) {
  var objOne = $('.' + ClassOne);
  var objTwo = $('.' + ClassTwo);
  var objOneOffset = objOne.offset();
  var objTwoOffset = objTwo.offset();
  //对象一横向，纵向最大值，起点
  var maxXOne = objOneOffset.left + objOne.width();
  var maxYOne = objOneOffset.top + objOne.height();
  var xOne = objOneOffset.left;
  var yOne = objOneOffset.top;
  //对象二横向，纵向最大值，起点
  var maxXTwo = objTwoOffset.left + objTwo.width();
  var maxYTwo = objTwoOffset.top + objTwo.height();
  var xTwo = objTwoOffset.left;
  var yTwo = objTwoOffset.top;
  //将所的X Y轴上的值放入数据中，排序取得各自中间值。
  var xArray = Array();
  xArray[0] = xOne;
  xArray[1] = xTwo;
  xArray[2] = maxXOne;
  xArray[3] = maxXTwo;
  xArray.sort(function(a, b) {
    return a > b ? 1 : -1
  });
  var yArray = Array();
  yArray[0] = yOne;
  yArray[1] = yTwo;
  yArray[2] = maxYOne;
  yArray[3] = maxYTwo;
  yArray.sort(function(a, b) {
    return a > b ? 1 : -1
  });
  if (xOne == xTwo && yOne == yTwo) {
    return true;
  }
  //得到X轴上的中值
  var mXV = (xArray[1] + xArray[2]) / 2;
  //得到Y轴上的中间值
  var mYV = (yArray[1] + yArray[2]) / 2;
  var xVar = mXV >= xOne && mXV <= maxXOne && mXV >= xTwo && mXV <= maxXTwo;
  var yVar = mYV >= yOne && mYV <= maxYOne && mYV >= yTwo && mYV <= maxYTwo;
  if (xVar && yVar) {
    return true;
  } else {
    return false;
  }
}
